<template>
  <div>
    <h2 class="page-title">
      <el-icon><User /></el-icon>
      个人信息
    </h2>
    <div class="card">
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="用户ID">
          <el-input v-model="form.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="form.userName"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="form.realName" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="form.phone"
            disabled
            placeholder="手机号不可修改"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-input v-model="form.userRole" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户头像" prop="userAvatar">
          <el-input
            v-model="form.userAvatar"
            placeholder="请输入头像URL"
          ></el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="userProfile">
          <el-input
            v-model="form.userProfile"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form.createTime" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存修改
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { User } from "@element-plus/icons-vue";
import { getCurrentUser, updateSelfProfile } from "@/api/user";

export default {
  name: "UserProfile",
  setup() {
    const formRef = ref(null);
    const loading = ref(false);
    const submitting = ref(false);
    const originalForm = ref({});

    const form = reactive({
      id: "",
      userName: "",
      realName: "",
      phone: "",
      userRole: "",
      userAvatar: "",
      userProfile: "",
      createTime: "",
    });

    const rules = reactive({
      userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      userProfile: [
        { max: 500, message: "个人简介不能超过500个字符", trigger: "blur" },
      ],
    });

    // 获取当前用户信息
    const fetchUserInfo = async () => {
      loading.value = true;
      try {
        const response = await getCurrentUser();
        console.log("[UserProfile] getCurrentUser response:", response);
        if (response.code === 0 && response.data) {
          const userData = response.data;
          Object.assign(form, {
            id: userData.id || "",
            userName: userData.userName || "",
            realName: userData.realName || "",
            phone: userData.phone || "",
            userRole: userData.userRole || "",
            userAvatar: userData.userAvatar || "",
            userProfile: userData.userProfile || "",
            createTime: userData.createTime || "",
          });
          // 保存原始数据用于重置
          originalForm.value = { ...form };
        } else {
          ElMessage.error(response.message || "获取用户信息失败");
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        ElMessage.error("获取用户信息失败，请重试");
      } finally {
        loading.value = false;
      }
    };

    // 提交修改
    const handleSubmit = () => {
      if (!formRef.value) return;

      formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true;
          try {
            // 重要：不要包含phone字段，因为个人资料更新不允许修改手机号
            const updateData = {
              id: form.id,
              userName: form.userName,
              userAvatar: form.userAvatar,
              userProfile: form.userProfile,
              updateTime: new Date().toISOString(),
            };

            console.log("[UserProfile] 提交的数据:", updateData);

            const response = await updateSelfProfile(updateData);
            console.log("[UserProfile] updateSelfProfile response:", response);

            if (response.code === 0) {
              ElMessage.success("修改成功");
              // 重新获取用户信息
              await fetchUserInfo();
            } else {
              // 显示具体的错误信息
              console.error("[UserProfile] 更新失败:", response);
              ElMessage.error(response.message || "修改失败");

              // 如果是手机号格式错误，但我们已经移除了phone字段，可能是其他问题
              if (response.message && response.message.includes("手机号")) {
                ElMessage.warning("提示：个人资料更新不允许修改手机号");
              }
            }
          } catch (error) {
            console.error("修改个人信息失败:", error);
            ElMessage.error("修改失败，请重试");
          } finally {
            submitting.value = false;
          }
        }
      });
    };

    // 重置表单
    const handleReset = () => {
      if (formRef.value) {
        formRef.value.resetFields();
      }
      Object.assign(form, originalForm.value);
    };

    onMounted(() => {
      fetchUserInfo();
    });

    return {
      User,
      formRef,
      form,
      rules,
      loading,
      submitting,
      handleSubmit,
      handleReset,
    };
  },
};
</script>

<style scoped>
.page-title {
  font-size: 20px;
  margin-bottom: 20px;
  color: #1b9a7c;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-title .el-icon {
  font-size: 24px;
}

.card {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

:deep(.el-form) {
  max-width: 600px;
}
</style>
